package com.ruoyi.common.core.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * AUTH tonkenController 方法 设置特殊的向下传递获取 租户ID方式
 * 因为 tonkenController 的方法，不会在网关层设置 token,无法通过 SecurityContextHolder获取
 */
public class AuthTenantContextHolder {

    private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();

    public static void set(String key, Object value)
    {
        Map<String, Object> map = getLocalMap();
        map.put(key, value == null ? StringUtils.EMPTY : value);
    }

    public static String get(String key)
    {
        Map<String, Object> map = getLocalMap();
        return Convert.toStr(map.getOrDefault(key, StringUtils.EMPTY));
    }

    public static <T> T get(String key, Class<T> clazz)
    {
        Map<String, Object> map = getLocalMap();
        return StringUtils.cast(map.getOrDefault(key, null));
    }

    public static Map<String, Object> getLocalMap()
    {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null)
        {
            map = new ConcurrentHashMap<String, Object>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    public static String getTenantId()
    {
        return get(SecurityConstants.TENANT_ID);
    }

    public static void setTenantId(String tenantId)
    {
        set(SecurityConstants.TENANT_ID, tenantId);
    }

    public static void remove()
    {
        THREAD_LOCAL.remove();
    }

}
